
<template>
  <div class="amap-box">
    <el-autocomplete v-model="address" :fetch-suggestions="searchAddres" placeholder="请输入地址搜索" @select="handleSelect" style="width:100%" v-if="search">
      <template slot-scope="{ item }">
        <div class="addr-item">
          <p class="name">{{ item.value }}</p>
          <p class="addr">{{ item.name }}</p>
        </div>
      </template>
    </el-autocomplete>
    <div class="amap" :id="mapId" :style="{'height':height}"></div>
  </div>
</template>
<script>
export default {
  props: {
    value: null,
    height: {
      type: String,
      default: "200px",
    },
    search: {
      type: Boolean,
      default: false,
    },
    position: {
      type: Object,
      default: () => {
        return {} // lng: 104.151663, lat: 30.627207, 
      },
    },
    zoom: {
      type: Number,
      default: 13,
    },
    makers: {
      type: Array,
      default: () => { return [] },
    },
    actived: {
      type: Number,
      default: -1,
    }
  },
  components: {
  },
  data() {
    return {
      mapId: "",
      map: null,
      address: "",
      center: null,
      markerList: [],
      mapMarkers: [],
    };
  },
  created() {
    this.mapId = "amap" + new Date().getTime();
  },
  mounted() {
    this.address = this.value;
    this.center = this.position;
    this.center.id = "center";
    setTimeout(() => {
      this.setMap();
    });
  },
  watch: {
    value() {
      this.address = this.value;
    },
    address(val) {
      this.$emit("input", val);
    },
    position(newVal, oldVal) {
      if ((!oldVal.lng || !oldVal.lng)) {
        this.center = this.position;
        this.center.id = "center";
        this.setMap();
      }
    },
    makers() {
      this.setMakers();
    },
    actived() {
      this.setMakers();
    }
  },
  methods: {
    setMap(callback) {
      var config = {
        zoom: this.zoom,
      }
      if (this.center.lat && this.center.lng) {
        config.center = [this.center.lng, this.center.lat];
      }
      if (this.map) {
        if (config.center) {
          this.map.setCenter(config.center);
        }
      } else {
        this.map = new AMap.Map(this.mapId, config);
      }
      this.setMakers();
      if (typeof callback == "function") {
        callback();
      }
    },
    setMakers() {
      let makers = [];
      this.mapMarkers = this.func.depCopy(this.makers);
      if (this.mapMarkers.length == 0) {
        this.mapMarkers.push(this.center);
      }
      this.mapMarkers.map((item, index) => {
        if (item.lat && item.lng) {
          makers.push({
            icon: new AMap.Icon({
              image: this.actived == index ? '/static/img/marker-blue.png' : '/static/img/marker-red.png',
              imageSize: new AMap.Size(28, 28) //图标大小
            }),
            extData: item,
            anchor: 'bottom-center',
            draggable: this.search,
            offset: new AMap.Pixel(0, 0),
            position: new AMap.LngLat(item.lng, item.lat),
          })
        }
      })
      this.addMaker(makers);
    },
    addMaker(markerList) {
      this.map.remove(this.markerList);
      this.markerList = [];
      markerList.map(item => {
        const marker = new AMap.Marker(item);
        this.map.add(marker);
        this.markerList.push(marker);
      })
      setTimeout(() => {
        this.markerDrag();
        this.markerClick();
      }, 200);
    },
    markerDrag() {
      this.markerList.map((marker, index) => {
        marker.on('dragend', data => {
          if (index == 0) {
            this.center.lng = data.lnglat.lng;
            this.center.lat = data.lnglat.lat;
            this.$emit("change", this.center);
            let position = [data.lnglat.lng, data.lnglat.lat] //位置的经纬度 
            new AMap.plugin("AMap.Geocoder", () => {
              const geocoder = new AMap.Geocoder();
              geocoder.getAddress(position, (status, result) => {
                if (status === "complete" && result.info === "OK") {
                  this.address = result.regeocode.formattedAddress;
                }
              });
            });
          }
        });
      })
    },
    markerClick() {
      this.markerList.map((marker, index) => {
        marker.on('click', data => {
          let extData = marker.getExtData();
          extData.type = "marker";
          this.$emit("click", extData);
        });
      })
    },
    searchAddres(query, cb) {
      AMap.plugin('AMap.AutoComplete', () => {
        var autoOptions = {
          //city 限定城市，默认全国
          city: '全国',
        };
        // 实例化AutoComplete
        var autoComplete = new AMap.AutoComplete(autoOptions);
        // 根据关键字进行搜索
        autoComplete.search(query, (status, result) => {
          // 搜索成功时，result即是对应的匹配数据
          if (status === "complete" && result.info === "OK") {
            var datas = result.tips || [];
            datas.map(item => {
              item.value = item.district + item.address;
            })
            cb(datas);
          } else {
            cb([]);
          }
        })
      })
    },
    handleSelect(item) {
      this.center = item.location;
      this.setMap();
      this.$emit("change", this.center);
    }
  },
}
</script>
<style>
.amap-logo {
  display: none !important;
}

.amap-copyright {
  visibility: hidden !important;
}
</style>
<style lang="scss" scoped>
.amap-box {
  position: relative;
  .amap {
    width: 100%;
    border: 1px solid #e6e6e6;
    background-color: #f9f9f9;
    margin-top: 10px;
  }

  .addr-item {
    padding: 4px 0;
  }

  .addr-item p {
    line-height: 1.4;
    font-size: 15px;
  }

  .addr-item .addr {
    font-size: 13px;
    color: #999;
  }
}
</style>